package cn.roadtrip.appgateway;

import cn.roadtrip.utilmodule.util.JWTHelper;
import cn.roadtrip.utilmodule.util.TokenValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
@Slf4j
public class GatewayValidFilter implements GlobalFilter, Ordered {


    @Autowired
    private JWTHelper jwtHelper;

    /**
     * 配套 max-in-memory，设置body限制大小问题
     *
     * @param codecConfigurer
     * @return
     */
    @Bean
    public List<HttpMessageReader<?>> messageReaders(ServerCodecConfigurer codecConfigurer) {
        return codecConfigurer.getReaders();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        String url = req.getURI().getPath();
//        log.info("请求的url：{}", url);
        if (url.contains("/login") || url.contains("/registry")) {
//            log.info("这里可能异常了");
            return chain.filter(
                    exchange.mutate().request(req).response(exchange.getResponse()).build()
            );
        }
        //获取header中的token
        String token = req.getHeaders().getFirst("utoken");//token值
        String direct = req.getHeaders().getFirst("direct");//模块方向
        String clientCode = req.getHeaders().getFirst("clientCode");//客户端码

        TokenValue tokenValue = null;
        try {
            tokenValue = jwtHelper.parseToken(token);
            if (jwtHelper.existKeyTokenValue(tokenValue)) {
                throw new RuntimeException("query-token-null");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        ServerHttpResponse rsp = exchange.getResponse();

        Long t = System.currentTimeMillis();
        return chain.filter(
                        exchange.mutate().request(req).response(rsp).build()
                )
                .then(
                        Mono.fromRunnable(() -> {
                            log.info("返回，时间差：{}", (System.currentTimeMillis() - t));
                        })
                );
    }


    @Override
    public int getOrder() {
        return -100;
    }
}
